package com.atguigu.common.valid.validator;


import com.atguigu.common.valid.anno.ListValue;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class ListValueConstraintValidator implements ConstraintValidator<ListValue, Integer> {

    private int[] vals;

    /**
     * constraintAnnotation 是在 POJO 的 属性上已经填写好值的注解
     * @param constraintAnnotation annotation instance for a given constraint declaration
     */
    @Override
    public void initialize(ListValue constraintAnnotation) {
        vals = constraintAnnotation.values();
    }

    /**
     * value 是需要被校验的值
     * @param value object to validate
     * @param context context in which the constraint is evaluated
     *
     * @return
     */
    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        if(value == null)
            return false;

        for(int i = 0; i < vals.length; i++) {
            if(vals[i] == value) {
                return true;
            }
        }
        return false;
    }
}
